package com.shujia.core

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

object Demo07GroupBy {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
    conf.setAppName("Demo07GroupBy")
    conf.setMaster("local")

    val sc: SparkContext = new SparkContext(conf)

    val stuLineRDD: RDD[String] = sc.textFile("spark/data/students.txt")

    // 将每条数据转换成样例类对象
    val stuRDD: RDD[StuGrp] = stuLineRDD.map(line => {
      val splits: Array[String] = line.split(",")
      StuGrp(splits(0), splits(1), splits(2).toInt, splits(3), splits(4))
    })

    /**
     * groupBy 按照指定的字段进行分组
     */
    // 按照性别分组，统计性别人数
    stuRDD
      .map(stu => (stu.gender, 1))
      .groupBy(_._1)
      .map(kv => (kv._1, kv._2.size))
      .foreach(println)

    // 统计班级人数
    stuRDD
      .map(stu => (stu.clazz, 1))
      .groupBy(_._1)
      .map(kv => (kv._1, kv._2.size))
      .foreach(println)


  }

  case class StuGrp(id: String, name: String, age: Int, gender: String, clazz: String)

}
